#include "stdafx.h"

#include "Logger.h"

#include <log4cplus/logger.h>
#include <log4cplus/FileAppender.h>
#include "Utils/SimpleStringCoder.h"
#include "Utils/Formatter.h"
#include "Utils/TimeUtils.h"

using namespace log4cplus;
using namespace log4cplus::helpers;

static log4cplus::Logger& GetLogger()
{
	static bool isCreated = false;
	static log4cplus::Logger logger = log4cplus::Logger::getInstance(_T("all"));
	if (!isCreated)
	{
		const int LOG_FILE_SIZE = 50*1024*1024;
		const int LOG_FILE_COUNT = 5; 
		char exeName[MAX_PATH] = "";
		::GetModuleFileName(NULL,exeName,1024);
		char logFile[1024] = "";
		SYSTEMTIME st = {0};
		::GetLocalTime(&st);
		sprintf_s(logFile,"%s-%02d-%02d.slg",exeName,st.wMonth,st.wDay);
		SharedAppenderPtr appender(new RollingFileAppender(logFile, LOG_FILE_SIZE,LOG_FILE_COUNT,true));
		appender->setName(_T("all"));

		log4cplus::tstring pattern = _T("%p\t%D{%Y-%m-%d %H:%M:%S.%Q} [%t]: `%m`%n");
		std::auto_ptr<Layout> layout(new PatternLayout(pattern));

		appender->setLayout(layout);
		logger.addAppender(appender);
		isCreated = true;
	}
	return logger;
}

void LightLogger::Debug(char const* msg)
{
	FT formatter("MS[%I64d] %s",MyGetTickCount(),msg);
#ifdef NDEBUG
	char buff[8192] = "";
	LOG4CPLUS_DEBUG(GetLogger(), SimpleStringCoder::Encode(formatter,buff,4096));
#else
	LOG4CPLUS_DEBUG(GetLogger(), formatter);
#endif
}

void LightLogger::Info(char const* msg)
{
	FT formatter("MS[%I64d] %s",MyGetTickCount(),msg);
#ifdef NDEBUG
	char buff[8192] = "";
	LOG4CPLUS_INFO(GetLogger(), SimpleStringCoder::Encode(formatter,buff,4096));
#else
	LOG4CPLUS_INFO(GetLogger(), formatter);
#endif
}

void LightLogger::Warn(char const* msg)
{
	FT formatter("MS[%I64d] %s",MyGetTickCount(),msg);
#ifdef NDEBUG
	char buff[8192] = "";
	LOG4CPLUS_WARN(GetLogger(), SimpleStringCoder::Encode(formatter,buff,4096));
#else
	LOG4CPLUS_WARN(GetLogger(), formatter);
#endif
}

void LightLogger::Error(char const* msg)
{
	FT formatter("MS[%I64d] %s",MyGetTickCount(),msg);
#ifdef NDEBUG
	char buff[8192] = "";
	LOG4CPLUS_ERROR(GetLogger(), SimpleStringCoder::Encode(formatter,buff,4096));
#else
	LOG4CPLUS_ERROR(GetLogger(), formatter);
#endif
}

void LightLogger::Fatal(char const* msg)
{
	FT formatter("MS[%I64d] %s",MyGetTickCount(),msg);
#ifdef NDEBUG
	char buff[8192] = "";
	LOG4CPLUS_FATAL(GetLogger(), SimpleStringCoder::Encode(formatter,buff,4096));
#else
	LOG4CPLUS_FATAL(GetLogger(), formatter);
#endif
}
